const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database().collection("user")

exports.main = async (event, context) => {
  // 获取 user 表的集合对象
  let username = event.username
  let password = event.password
  console.log('账号', username, '密码', password)

  if (username == '' || pass1 == '') {
    wx.showToast({
      title: '用户或密码不能为空',
      icon: 'none',
      duration: 2000
    })
  } else {
    //登陆
    db.where({
      sid: username
    }).get({

      success(res) {
        console.log("获取数据成功", res)
        if (res.data.length == 0) {
          console.log('登陆失败')
          wx.showToast({
            icon: 'none',
            title: '账号不存在,请重新输入',
          })

        } else {
          let user = res.data
          console.log("user", user)
          if (  password == user.password ) {
            console.log('登陆成功')
            wx.showToast({
              title: '登陆成功',
            })
            console.log("user", user)
            //保存用户登陆状态
            wx.setStorageSync('user', user)
            //页面跳转
            wx.switchTab({
              url: '../personal/personal'
            })

          } else {
            console.log('登陆失败')
            wx.showToast({
              icon: 'none',
              title: '账号或密码不正确',
            })
          }
        }
      },
      fail(res) {
        console.log("获取数据失败", res)
      }
    })
  }

}